from utils.word.core_word import WordAnalyzer
from utils.common.db import DBConnector
from utils.common.logger import log


class CoreCaller:
    def __init__(self, db_config: dict = None):
        self.word_analyzer = None
        self.db_config = db_config

    def search_tag(self, tag: str, more_info: list = [], N: int = 100):
        """
        根据用户输入的标签/专题，寻找最为相关的前N条
        """

        db = DBConnector(self.db_config)
        if db.connect() == False:
            log.logger.warning("Cannot connect to database!")
            return None

        if self.word_analyzer is None:
            self.word_analyzer = WordAnalyzer()

        # 将专题分词，进行细粒度匹配
        pair_list = self.word_analyzer.seg(tag)

        dbData = db.query(
            "select news_id,title,keywords from main where content is not null and keywords is not null")

        news_dict = {}
        for news in dbData:
            id = news["news_id"]
            news_dict[id] = 0  # 先把每个新闻对应的相关度设为0

            # 先对分词进行匹配，其权值最低
            for word in pair_list:
                news_dict[id] += (news["title"] +
                                  news["keywords"]).count(word)*0.2

            # 再对more_info进行匹配，权值较高
            for detail in more_info:
                news_dict[id] += (news["title"] +
                                  news["keywords"]).count(detail)*0.4

            # 若关键词直接出现，则优先匹配
            news_dict[id] += (news["title"] +
                              news["keywords"]).count(tag)*0.4

            if news_dict[id] == 0:
                news_dict.pop(id)

        return sorted(news_dict.items(), key=lambda x: x[1], reverse=True)[:N]
